var wsCommon = {
    host: "index.htm",
    // host: "http://testme.chijiayd.com",
    domainhost: "index.htm",
    jsonType: "jsonp",
    getUrlParam: function(name) {
           var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
           var r = window.location.search.substr(1).match(reg);  //匹配目标参数
           if (r != null) return unescape(r[2]); return null; //返回参数值
    },
    setCookie: function(name, value) {
        var Days = 30;
         var exp = new Date();
         exp.setTime(exp.getTime() + Days*24*60*60*1000);
         document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    },
    getCookie: function(name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
         if(arr=document.cookie.match(reg))
         return unescape(arr[2]);
         else
         return null;
    },
    delCookie: function(name) {
        var exp = new Date();
         exp.setTime(exp.getTime() - 1);
         var cval=wsCommon.getCookie(name);
         if(cval!=null)
         document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }
}

$(function() {
    var totalNum = 0;
    var totalPrice = 0;
    var goodsStyleNum = 0;

    window.common = {
        setTopUserInfo: function() {
            // var uid = wsCommon.getCookie('uid');
            // if(uid) {
                $.ajax({
                    url: wsCommon.host + '/api/member/queryUser',
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                if(typeof(res.data.user != 'undefined') && res.data.user != null) {
                                    $('#loginBar_576').hide();
                                    $('#memberBar_576').show();
                                    $('#uname_576').html(res.data.user.username);
                                    // 注册成功写入用户名
                                    if($('[data-role="registerSuccessName"]').length) {
                                        $('[data-role="registerSuccessName"]').html(res.data.user.username)
                                    }
                                }
                            }

                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            // }
        },
        toLogin: function() {
            $('.login-btn').on('click', function() {
                wsCommon.setCookie('go_back_link', window.location.href);
                window.location.href = 'login.htm';
            })
        },
        logout: function() {
            $(document).on('click', '[data-role="logout"]', function() {
                $.ajax({
                    url: wsCommon.host + '/api/member/logout',
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.code == 1) {
                            wsCommon.delCookie('uid');
                            window.location.href = 'index.htm';
                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            })
        },
        throttle: function(callback, wait) {
            var context, args, timeout, result;
            var previous = 0;
            var later = function () {
                previous = new Date;
                timeout  = null;
                result   = callback.apply(context, args);
            };
            return function () {
                var now = new Date;
                var remaining = wait - (now - previous);
                context = this;
                args = arguments;
                if (remaining <= 0) {
                    clearTimeout(timeout);
                    timeout  = null;
                    previous = now;
                    result   = callback.apply(context, args);
                } else if (!timeout) {
                    timeout = setTimeout(later, remaining);
                }
                return result;
            };
        },
        listShopCart: function() {
            /**购物车**/
            $(".minicart").on('mouseenter', common.throttle(function() {
                $(this).addClass("minicart-active");
                totalNum = 0;
                totalPrice = 0;
                goodsStyleNum = 0;

                common.listShopCartAjax(function(res) {
                    common.renderListShopCart(res);
                });
            }, 200)).on('mouseleave', function() {
                $(this).removeClass("minicart-active");
                $('[data-role="shopCartLoading"]').show();
                $('[data-role="minicart-cont"]').html('');
            })

        },
        renderListShopCart: function(res) {
            $('[data-role="shopCartLoading"]').hide();
            var cartList = res.data == null ? [] : res.data.cartList;
            var cartListTpl = '';

            if(!cartList || cartList.length == 0) {
                $('[data-role="shopCartnon"]').show();
                $('.op-cart-number').html(0);
            } else {
                $('[data-role="shopCartnon"]').hide();
                cartListTpl += '<ul class="minicart-list clearfix">';
                $.each(cartList, function(index, item) {
                    var params = JSON.parse(item.params);
                    var link = '';
                    if(item.objIdentArray[3] == 3) {
                        link = '/info-give.html?goodsId='+item.objIdentArray[1]+'&catId='+JSON.parse(item.params).catId+'';
                    } else {
                        link = '/info.html?goodsId='+item.objIdentArray[1]+'&catId='+JSON.parse(item.params).catId+'';
                    }
                    cartListTpl += '<li class="goods-item">\
                                       <div class="goods-pic">\
                                               <a href="'+link+'"><img src="'+params.image.murl+'"></a>\
                                       </div>\
                                       <div class="goods-info">\
                                         <h3 class="goods-name"><a href="'+link+'">'+params.productName+'</a></h3>\
                                         <div class="goods-price">\
                                           <p>销售价：<span class="p-price">¥'+params.price+'</span></p>\
                                           <p>数量：<span class="p-quantity">'+item.quantity+'</span><span style="cursor:pointer;" class="action-delete" data-objIdent="'+item.objIdent+'"  data-delprice="'+params.price+'" data-delquantity="'+item.quantity+'">移除</span></p>\
                                         </div>\
                                       </div>\
                                    </li>';
                    goodsStyleNum++;
                    totalNum += item.quantity;
                    if(params.specPrice != null) {
                        totalPrice += params.specPrice * item.quantity;
                    } else {
                        totalPrice += params.price * item.quantity;
                    }

                });

                cartListTpl += '</ul><div class="minicart-info">\
                                    <p>共 <i>'+goodsStyleNum+'</i> 种商品，数量共 <i>'+totalNum+'</i> 件<br>金额总计：<span class="price">¥'+totalPrice.toFixed(2)+'</span></p>\
                                    <p> <a href="/cart1.html" class="btn-tocart">去结算</a> </p>\
                                </div>';
            }

            $('.op-cart-number').html(totalNum)

            $('[data-role="minicart-cont"]').html(cartListTpl);
        },
        slideListShopCart: function() {
            // 添加购物车弹窗关闭
            $("#mini_cart_dialog .popup-btn-close").click(function(){
    			$("#mini_cart_dialog").hide();
                // $('[data-role="slideShopCartLoading"]').show();
    		})

            var height = $(window).height() - 126;
            $(window).on('resize', common.throttle(function() {
                height = $(window).height() - 126;
                $('.minicart-list').css({
                    'height': height + 'px',
                    'overflow-y': 'scroll'
                })
            }, 200))
            var isCarShow = false;
            //迷你购物车
            $('#car').on('click', function() {
                if(isCarShow) {

                    $(".ioc_index,#floatDivBoxs").animate({right:"0px"}, 'fast', function() {
                        $("#floatDivBoxs").find(".minicart-cont").hide();
                    });
                    $("#floatDivBoxs").find(".minicart-cont").animate({right:'-300px'}, 'fast', function() {
                        $('[data-role="slideShopCartLoading"]').show();
                        $('[data-role="shopCartnon"]').hide();
                        $('[data-role="slideShopCart"]').html('');
                    });

                } else {
                    $('[data-role="shopCartnon"]').hide();
                    totalNum = 0;
                    totalPrice = 0;
                    goodsStyleNum = 0;
                    common.listShopCartAjax(function(res) {
                        common.renderSlideListShopCart(res);
                    });

                    $("#floatDivBoxs").find(".minicart-cont").show();
                    $(".ioc_index,#floatDivBoxs").animate({right:"300px"},'fast', function() {
                        $('.minicart-list').css({
                            'height': height + 'px',
                            'overflow-y': 'scroll'
                        })
                    });
                    $("#floatDivBoxs").find(".minicart-cont").animate({right:'0'}, 'fast')
                }

                isCarShow = !isCarShow;
            })

            $("#floatDivBoxs .popup-btn-close").click(function(){
                isCarShow = false;
                $("#floatDivBoxs").find(".minicart-cont").animate({right:'-300px'}, 'fast')
                $(".ioc_index,#floatDivBoxs").animate({right:"0px"},'fast', function() {
                    $('[data-role="slideShopCartLoading"]').show();
                    $('[data-role="shopCartnon"]').hide();
                    $('[data-role="slideShopCart"]').html('');
                });
            });
        },
        renderSlideListShopCart: function(res) {
            var cartList = res.data == null ? [] : res.data.cartList;
            var cartListTpl = '';

            if(!cartList || cartList.length == 0) {
                $('[data-role="shopCartnon"]').show();
                $('.op-cart-number').html(0);
            } else {
                $('[data-role="shopCartnon"]').hide();
                cartListTpl += '<ul class="minicart-list clearfix">';
                $.each(cartList, function(index, item) {
                    var params = JSON.parse(item.params);
                    var link = '';
                    if(item.objIdentArray[3] == 3) {
                        link = '/info-give.html?goodsId='+item.objIdentArray[1]+'&catId='+item.catId+'';
                    } else {
                        link = '/info.html?goodsId='+item.objIdentArray[1]+'&catId='+item.catId+'';
                    }
                    cartListTpl += '<li class="goods-item">\
                                       <div class="goods-pic">\
                                               <a href="'+link+'"><img src="'+params.image.murl+'"></a>\
                                       </div>\
                                       <div class="goods-info">\
                                         <h3 class="goods-name"><a href="'+link+'">'+params.productName+'</a></h3>\
                                         <div class="goods-price">\
                                           <p>销售价：<span class="p-price">¥'+params.price+'</span></p>\
                                           <p>数量：<span class="p-quantity">'+item.quantity+'</span><span style="cursor:pointer;" class="action-delete" data-objIdent="'+item.objIdent+'" data-delprice="'+params.price+'" data-delquantity="'+item.quantity+'">移除</span></p>\
                                         </div>\
                                       </div>\
                                    </li>';
                    goodsStyleNum++;
                    totalNum += item.quantity;
                    if(params.specPrice != null) {
                        totalPrice += params.specPrice * item.quantity;
                    } else {
                        totalPrice += params.price * item.quantity;
                    }
                });

                cartListTpl += '</ul><div class="minicart-info">\
                                    <p>共 <i>'+goodsStyleNum+'</i> 种商品，数量共 <i>'+totalNum+'</i> 件<br>金额总计：<span class="price">¥'+totalPrice.toFixed(2)+'</span></p>\
                                    <p> <a href="/cart1.html" class="btn-tocart">去结算</a> </p>\
                                </div>';
            }

            $('[data-role="slideShopCartLoading"]').hide();

            $('[data-role="slideShopCart"]').html(cartListTpl);
        },
        listShopCartAjax: function(cb) {
            $.ajax({
                url: wsCommon.host + '/api/cart/cartView',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    cb(res)
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },
        initShopCartNum: function() {
            common.listShopCartAjax(function(res) {
                var cartList = res.data.cartList == null ? [] : res.data.cartList;
                $.each(cartList, function(index, item) {
                    var params = JSON.parse(item.params);
                    totalNum += item.quantity;
                    goodsStyleNum++;
                    totalPrice += item.quantity * params.price;
                })

                $('.op-cart-number').html(totalNum)
            })
        },

        // 添加到购物车
        addShopCart: function() {
            $(document).on('click', '[data-role="addShopCart"]', function() {
                var $this = $(this);

                var quantity;
                if($this.attr('data-style') == 'info') {
                    quantity = Number($this.closest('li').prev('li').find('.action-quantity-input').val());
                } else {
                    quantity = Number($this.prev('.p-quantity').find('.action-quantity-input').val()) || 1;
                }

                $.ajax({
                    url: wsCommon.host + '/api/cart/addGoods',
                    data: {
                        goodsId: $this.attr('data-goodsid'),
                        productId: $this.attr('data-productid'),
                        objType: $this.attr('data-objtype'),
                        quantity: quantity
                    },
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        var _thisoffset = $this.offset();
                        var ox;
                        var oy;
                        if($this.attr('data-style') == 'info') {
                            ox = _thisoffset.left+39;
                            oy = _thisoffset.top+182;
                        } else if($this.attr('data-style') == 'zt') {
                            ox = _thisoffset.left+110;
                            oy = _thisoffset.top+172;
                        } else {
                            ox = _thisoffset.left-8;
                            oy = _thisoffset.top+165;
                        }

                        if(res.code == 1) {
                            var data = (res.data == null) ? [] : res.data;

                            totalNum = 0;
                            totalPrice = 0;
                            goodsStyleNum = 0;
                            $.each(data, function(index, item) {
                                var params = JSON.parse(item.params);
                                totalNum += item.quantity;
                                goodsStyleNum++;
                                if(params.specPrice != null) {
                                    totalPrice += item.quantity * params.specPrice;
                                } else {
                                    totalPrice += item.quantity * params.price;
                                }
                            })
                            $('.op-cart-number').html(totalNum);

             				$("#mini_cart_dialog")
                            .find('.caution-content').html('加入购物车成功。<br>目前选购商品共<em>'+goodsStyleNum+'</em>种<em>'+totalNum+'</em>件。合计：<i class="price">¥'+totalPrice.toFixed(2)+'</i>').end()
                            .css({
             				  "left": ox + 'px',
             				  "top": oy + 'px',
             				}).show();
                        } else {
                            if(res.code == -5) {
                                // var _thisoffset = $this.offset();
                 			// 	var ox = _thisoffset.left-8;
                 			// 	var oy = _thisoffset.top+165;
                                $("#mini_cart_dialog")
                                .find('.caution-content').html('库存不足').end()
                                .css({
                 				  "left": ox,
                 				  "top": oy,
                 				}).show();
                            } else {
                                // var _thisoffset = $this.offset();
                 			// 	var ox = _thisoffset.left-8;
                 			// 	var oy = _thisoffset.top+165;
                                $("#mini_cart_dialog")
                                .find('.caution-content').html('加入购物车失败').end()
                                .css({
                 				  "left": ox,
                 				  "top": oy,
                 				}).show();
                            }
                        }

                    },
                    error: function() {
                        // console.log('添加到购物车显示接口返回失败');
                    }
                })
            })
        },

        // 删除购物车商品（单个）
        deleteSingleShopCart: function() {
            $(document).on('click', '.action-delete', function() {
                var $this = $(this);

                $.ajax({
                    url: wsCommon.host + '/api/cart/delCart',
                    data: {
                        objIdent: $(this).attr('data-objident')
                    },
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.reason == 'success') {
                            var data = (res.data == null || res.data == '') ? [] : res.data;

                            goodsStyleNum -= 1;
                            if(goodsStyleNum == 0) {
                                totalNum = 0;
                                totalPrice = 0;
                                $('[data-role="shopCartnon"]').show();
                                $('.minicart-info').remove();
                            } else {
                                $('[data-role="shopCartnon"]').hide();
                                totalNum -= $this.attr('data-delquantity');
                                totalPrice -= $this.attr('data-delprice') * $this.attr('data-delquantity');
                                $('.minicart-info').html('<p>共 <i>'+goodsStyleNum+'</i> 种商品，数量共 <i>'+totalNum+'</i> 件<br>金额总计：<span class="price">¥'+totalPrice.toFixed(2)+'</span></p><p> <a href="/cart1.html" class="btn-tocart">去结算</a> </p>')
                            }
                            $this.closest('.goods-item').hide();
                            $('.op-cart-number').html(totalNum)
                        } else {
                            // console.log('删除失败');
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        // console.log('购物车商品单个删除接口返回失败');
                    }
                })
            })
        },
        // 显示金额
        showMoney: function(index, res) {
            if(window.location.href.indexOf('cart1') != -1) {
                $('[data-role="allMoney"]').html('¥' + res.data.payResultInfo.totalMoney);
                $('[data-role="saveMoney"]').html('¥' + res.data.payResultInfo.savedMoney);
                $('[data-role="totalMoney"]').html('¥' + res.data.payResultInfo.payMoney);
                $('.subtotal-integral').html(res.data.payResultInfo.giveScore + res.data.payResultInfo.totalNormalScore);

                if(index != undefined) {
                    var dom = $('#product_main_items_list tr').eq(index);
                    dom.find('[data-gwjs="saveMoney"]').html('¥' + res.data.buyInfoList[index].saveMoney);
                    // dom.find('[data-gwjs="score"]').html('¥' + res.data.buyInfoList[index].score);
                    dom.find('[data-gwjs="real"]').html('¥' + res.data.buyInfoList[index].subtotalPrice);
                }

                // 多级赠送
                var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;
                var giveObjInfostpl = '';
                if(giveObjInfos.length) {
                    $.each(giveObjInfos, function(index, item) {
                        if(item.showSelect) {
                            giveObjInfostpl += '<div class="djzs-item"><div>'+item.ruleName+'</div>';
                            $.each(item.giveObjInfoList, function(indexDir, itemDir) {
                                if(itemDir.fit) {
                                    giveObjInfostpl += '<div class="djzs-item__inner">\
                                                            <a href="/info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'">\
                                                                <img src="'+itemDir.picUrl+'" alt="'+itemDir.objName+'">\
                                                            </a>\
                                                            <div class="djzs-item__inners">\
                                                                <input type="radio" name="rule'+index+'" data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'">\
                                                                <a href="javascript:;" title="'+itemDir.objName+'">'+itemDir.objName+'</a>\
                                                            </div>\
                                                        </div>';
                                }
                            })
                            giveObjInfostpl += '</div>';
                        }
                    })
                    giveObjInfostpl += '<div class="djzs-submit">确定</div>';
                } else {
                    giveObjInfostpl += '无';
                }
                $('[data-role="djzs"]').html(giveObjInfostpl == '<div class="djzs-submit">确定</div>' ? '无' : giveObjInfostpl);

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(index, item) {
                    if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            obj[$(item).attr('data-objident')] = Number(i.val());
                        }
                    }
                })
                var objStr = JSON.stringify(obj)
                wsCommon.setCookie('cartIdentInfos', objStr);
            }
        },
        contorlNum: function() {
            //商品数量
            $(document).on('click', '.btn-decrease', function() {
                var $this = $(this);
                var $input = $this.next('input');
                var $x = $input.offset().left;
        		var $y = $input.offset().top;
                var total1 = $(this).attr('data-total');
                var index = $this.closest('tr').index();

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    // if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            if(indexDir == index) {
                                obj[$(item).attr('data-objident')] = Number(i.val()) - 1;
                            } else {
                                obj[$(item).attr('data-objident')] = Number(i.val());
                            }
                        }
                    // }
                })
                var objStr = JSON.stringify(obj)

                if($input.val() > 1) {
                    if($this.attr('data-page') == 'cart1') {
                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: Number($input.val()) - 1
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            xhrFields:{withCredentials:true},
                            type: 'post',
                            success: function(res) {
                                if(res.code == 1) {
                                    // if(!res.result) {
                                    //     wsCommon.setCookie('go_back_link', window.location.href);
                                    //     window.location.href = './passport-login.html';
                                    //     return;
                                    // }
                                    $input.val(parseInt($input.val())-1);
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) - 1);

                                    common.renderUpgrate(res);

                                    // 购物车结算
                                    if($('#product_main_items_list').length) {
                                        common.showMoney(index, res);
                                    }
                                } else {
                                    if(res.code == -5) {
                                        var tempcha = Number($input.val()) - Number($this.attr('data-total'));

                                        $.ajax({
                                            url: wsCommon.host + '/api/cart/updateCart',
                                            data: {
                                                updateInfo: JSON.stringify([
                                                    {
                                                        goodsId: $this.attr('data-goodsid'),
                                                        productId: $this.attr('data-productid'),
                                                        objType: $this.attr('data-objtype'),
                                                        quantity: Number($input.val()) - 1
                                                    }
                                                ]),
                                                cartIdentInfos: objStr
                                            },
                                            type: 'post',
                                            xhrFields:{withCredentials:true},
                                            success: function(res) {
                                                if(res.code == 1) {
                                                    // if(!res.result) {
                                                    //     wsCommon.setCookie('go_back_link', window.location.href);
                                                    //     window.location.href = './passport-login.html';
                                                    //     return;
                                                    // }
                                                    $input.val($this.attr('data-total'));
                                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) - tempcha);
                                                    $this.closest('.p-quantity').next('[data-role="tips"]').hide();
                                                    // var scoredom = $this.closest('td').next('td').next('td');
                                                    // scoredom.html(Number(scoredom.attr('data-score')) * Number($input.val()).toFixed(2));
                                                    // var chaeDom = scoredom.next('td');
                                                    // chaeDom.html('¥' + (Number(chaeDom.attr('data-chae')) * Number($input.val())).toFixed(2));
                                                    // var saveDom = $this.closest('td').next('td');
                                                    // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($input.val())).toFixed(2));

                                                    // var totalScore = 0;
                                                    // $.each($('[data-gwjs="score"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalScore += Number($(item).html());
                                                    //     }
                                                    // })
                                                    // $('.subtotal-integral').html(totalScore);
                                                    //
                                                    // var totalSavemony = 0;
                                                    // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalSavemony += Number($(item).html().substring(1));
                                                    //     }
                                                    // })
                                                    // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                                                    //
                                                    // var totalMoney = 0;
                                                    // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                                                    //     }
                                                    // })
                                                    // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                                                    //
                                                    // var totalRealMoney = 0;
                                                    // $.each($('[data-gwjs="real"]'), function(index,item) {
                                                    //     if($(item).closest('tr').attr('data-checked') == 1) {
                                                    //         totalRealMoney += Number($(item).html().substring(1));
                                                    //     }
                                                    // })
                                                    // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                                                    common.showMoney(index, res);
                                                }
                                            },
                                            error: function() {}
                                        })
                                    } else {
                                        iosOverlay({
                                            text: res.reason,
                                            duration: 1000
                                        });
                                    }
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
                    $input.val($this.next('input').val()-1)
                } else {
                    if(total1 == 0) {
                        $(this).closest('.p-quantity').next('p').show();
                    } else {
                        $("#xtips_txt").html("此商品的最小购买数量为1件");
        				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
        				setTimeout(function () {
        					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
        				}, 1500);
                    }
                }

                var total1 = $(this).attr('data-total');

                if($input.val() <= total1) {
                    $(this).closest('.p-quantity').next('p').hide();
                }


            })
            $(document).on('click', '.btn-increase', function() {
                var $this = $(this);
                var $input = $this.prev('input');
                var $x = $input.offset().left;
        		var $y = $input.offset().top;
                var maxStore = Number($this.attr('data-total'));
                var index = $this.closest('tr').index();

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    // if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            if(indexDir == index) {
                                if(Number(i.val()) >= maxStore) {
                                    obj[$(item).attr('data-objident')] = maxStore;
                                } else {
                                    obj[$(item).attr('data-objident')] = Number(i.val()) + 1;
                                }
                            } else {
                                obj[$(item).attr('data-objident')] = Number(i.val());
                            }
                        }
                    // }
                })
                var objStr = JSON.stringify(obj);

                if($input.val()>0 && $input.val() < maxStore) {
                    $this.closest('.p-quantity').next('[data-role="tips"]').hide();
                    if($this.attr('data-page') == 'cart1') {
                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: Number($input.val()) + 1
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            xhrFields:{withCredentials:true},
                            type: 'post',
                            success: function(res) {
                                if(res.code == 1) {
                                    // if(!res.result) {
                                    //     wsCommon.setCookie('go_back_link', window.location.href);
                                    //     window.location.href = './passport-login.html';
                                    //     return;
                                    // }
                                    $input.val(parseInt($input.val())+1);
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + 1);
                                    common.renderUpgrate(res);

                                    // 购物车结算
                                    if($('#product_main_items_list').length) {

                                        common.showMoney(index, res);
                                    }
                                } else {
                                    iosOverlay({
                                        text: res.reason,
                                        duration: 1000
                                    });
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
                    $input.val(parseInt($input.val())+1);
                } else {
                    $("#xtips_txt").html("此商品最多只能购买"+maxStore+"件");
    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    				setTimeout(function () {
    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    				}, 1500);
                }


            })

            // $(document).on('keyup', '.action-quantity-input', function() {
            //     var $this = $(this);
            //     var tmptxt=$this.val();
    		// 	$this.val(tmptxt.replace(/\D|^0/g,''));
            //     var $max = Number($this.attr('data-total'));
            //     var $x = $this.offset().left;
        	// 	var $y = $this.offset().top;
    		// 	if(tmptxt>$max){
    		// 		$(this).val($max);
    		// 		$("#xtips_txt").html("此商品最多只能购买"+$max+"件");
    		// 		$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    		// 		setTimeout(function () {
    		// 			$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    		// 		}, 1500);
            //
            //         // if($('#product_main_items_list').length) {
            //         //     var scoredom = $this.closest('td').next('td').next('td');
            //         //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
            //         //     var chaeDom = scoredom.next('td');
            //         //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
            //         // }
    		// 	}else if(tmptxt<1){
    		// 		$(this).val(1);
    		// 		$("#xtips_txt").html("此商品的最小购买数量为1件");
    		// 		$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    		// 		setTimeout(function () {
    		// 			$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    		// 		}, 1500);
            //         if($('#product_main_items_list').length) {
            //             // var scoredom = $this.closest('td').next('td').next('td');
            //             // scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
            //             // var chaeDom = scoredom.next('td');
            //             // chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
            //             // var saveDom = $this.closest('td').next('td');
            //             // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($this.val())));
            //
            //             // var totalScore = 0;
            //             // $.each($('[data-gwjs="score"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalScore += Number($(item).html());
            //             //     }
            //             // })
            //             // $('.subtotal-integral').html(totalScore);
            //             //
            //             // var totalSavemony = 0;
            //             // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalSavemony += Number($(item).html().substring(1));
            //             //     }
            //             // })
            //             // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
            //             //
            //             // var totalMoney = 0;
            //             // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
            //             //     }
            //             // })
            //             // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
            //             //
            //             // var totalRealMoney = 0;
            //             // $.each($('[data-gwjs="real"]'), function(index,item) {
            //             //     if($(item).closest('tr').attr('data-checked') == 1) {
            //             //         totalRealMoney += Number($(item).html().substring(1));
            //             //     }
            //             // })
            //             // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
            //             common.showMoney($this.closest('tr').index());
            //         }
    		// 	}
            // });
            var tempval = 0;
            $(document).on('focus', '.action-quantity-input', function() {
                var $this = $(this);
                var tmptxt=$this.val();
                tempval = tmptxt;
            })

            $(document).on('blur', '.action-quantity-input', function() {
                var $this = $(this);
                var tmptxt=$this.val();
    			$this.val(tmptxt.replace(/[^0-9\-]/g,''));
                var $max = Number($this.attr('data-total'));
                var $x = $this.offset().left;
        		var $y = $this.offset().top;

                var index = $this.closest('tr').index();

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    // if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            if(indexDir == index) {
                                if(Number(i.val()) > $max) {
                                    obj[$(item).attr('data-objident')] = $max;
                                } else if(Number(i.val()) < 1) {
                                    obj[$(item).attr('data-objident')] = 1;
                                } else {
                                    obj[$(item).attr('data-objident')] = Number(i.val());
                                }
                            } else {
                                obj[$(item).attr('data-objident')] = Number(i.val());
                            }
                        }
                    // }
                })
                var objStr = JSON.stringify(obj)

    			if(tmptxt>$max){
                    $this.closest('.p-quantity').next('[data-role="tips"]').show();
                    if($this.attr('data-page') == 'cart1') {

                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: $max
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            type: 'post',
                            xhrFields:{withCredentials:true},
                            success: function(res) {
                                if(res.code == 1) {
                                    // if(!res.result) {
                                    //     wsCommon.setCookie('go_back_link', window.location.href);
                                    //     window.location.href = './passport-login.html';
                                    //     return;
                                    // }
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + $max - tempval);
                                    $this.val($max);
                    				$("#xtips_txt").html("此商品最多只能购买"+$max+"件");
                    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
                    				setTimeout(function () {
                    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
                    				}, 1500);

                                    // if($('#product_main_items_list').length) {
                                    //     var scoredom = $this.closest('td').next('td').next('td');
                                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                                    //     var chaeDom = scoredom.next('td');
                                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                                    // }

                                    common.renderUpgrate(res);

                                    common.showMoney(index, res);
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }

    				$this.val($max);
    				$("#xtips_txt").html("此商品最多只能购买"+$max+"件");
    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    				setTimeout(function () {
    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    				}, 1500);

                    // if($('#product_main_items_list').length) {
                    //     var scoredom = $this.closest('td').next('td').next('td');
                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                    //     var chaeDom = scoredom.next('td');
                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                    // }
                    common.showMoney($this.closest('tr').index());
    			} else if(tmptxt<1){
                    if($this.attr('data-page') == 'cart1') {

                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: 1
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            type: 'post',
                            xhrFields:{withCredentials:true},
                            success: function(res) {
                                if(res.code == 1) {
                                    // if(!res.result) {
                                    //     wsCommon.setCookie('go_back_link', window.location.href);
                                    //     window.location.href = './passport-login.html';
                                    //     return;
                                    // }
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + 1 - tempval);
                                    $this.val(1);
                    				$("#xtips_txt").html("此商品的最小购买数量为1件");
                    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
                    				setTimeout(function () {
                    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
                    				}, 1500);
                                    // if($('#product_main_items_list').length) {
                                    //     var scoredom = $this.closest('td').next('td').next('td');
                                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                                    //     var chaeDom = scoredom.next('td');
                                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                                    // }

                                    common.renderUpgrate(res);

                                    common.showMoney(index, res);
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
    				$this.val(1);
    				$("#xtips_txt").html("此商品的最小购买数量为1件");
    				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-55,"top":$y-65});
    				setTimeout(function () {
    					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
    				}, 1500);
                    // if($('#product_main_items_list').length) {
                    //     var scoredom = $this.closest('td').next('td').next('td');
                    //     scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                    //     var chaeDom = scoredom.next('td');
                    //     chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                    // }
    			} else {
                    $this.closest('.p-quantity').next('[data-role="tips"]').hide();
                    if($this.attr('data-page') == 'cart1') {

                        $.ajax({
                            url: wsCommon.host + '/api/cart/updateCart',
                            data: {
                                updateInfo: JSON.stringify([
                                    {
                                        goodsId: $this.attr('data-goodsid'),
                                        productId: $this.attr('data-productid'),
                                        objType: $this.attr('data-objtype'),
                                        quantity: Number($this.val())
                                    }
                                ]),
                                cartIdentInfos: objStr
                            },
                            type: 'post',
                            xhrFields:{withCredentials:true},
                            success: function(res) {
                                if(res.code == 1) {
                                    // if(!res.result) {
                                    //     wsCommon.setCookie('go_back_link', window.location.href);
                                    //     window.location.href = './passport-login.html';
                                    //     return;
                                    // }
                                    $('.op-cart-number').html(Number($('.op-cart-number').html()) + Number($this.val()) - tempval);
                                    if($('#product_main_items_list').length) {
                                        common.renderUpgrate(res);

                                        common.showMoney(index, res);
                                    }
                                }
                            },
                            error: function() {}
                        })
                        return;
                    }
                    if($('#product_main_items_list').length) {
                        // var scoredom = $this.closest('td').next('td').next('td');
                        // scoredom.html(Number(scoredom.attr('data-score')) * Number($this.val()));
                        // var chaeDom = scoredom.next('td');
                        // chaeDom.html('¥' + Number(chaeDom.attr('data-chae')) * Number($this.val()));
                        // var saveDom = $this.closest('td').next('td');
                        // saveDom.html('¥' + (Number(saveDom.attr('data-save')) * Number($this.val())));

                        // var totalScore = 0;
                        // $.each($('[data-gwjs="score"]'), function(index,item) {
                        //     totalScore += Number($(item).html());
                        // })
                        // $('.subtotal-integral').html(totalScore);
                        //
                        // var totalSavemony = 0;
                        // $.each($('[data-gwjs="saveMoney"]'), function(index,item) {
                        //     totalSavemony += Number($(item).html().substring(1));
                        // })
                        // $('[data-role="saveMoney"]').html('¥' + totalSavemony.toFixed(2));
                        //
                        // var totalMoney = 0;
                        // $.each($('[data-gwjs="allMoney"]'), function(index,item) {
                        //     totalMoney += Number($(item).html().substring(1)) * Number($(item).next('td').find('input').val());
                        // })
                        // $('[data-role="allMoney"]').html('¥' + totalMoney.toFixed(2));
                        //
                        // var totalRealMoney = 0;
                        // $.each($('[data-gwjs="real"]'), function(index,item) {
                        //     totalRealMoney += Number($(item).html().substring(1));
                        // })
                        // $('[data-role="totalMoney"]').html('¥' + totalRealMoney.toFixed(2));
                        common.showMoney(index, res);
                    }
                }
            })
        },
        deleteAllShopCart: function() {
            $(document).on('click', '[data-role="delAll"]', function() {
                $.ajax({
                    url: wsCommon.host + '/api/cart/delAllCart',
                    dataType: wsCommon.jsonType,
                    success: function(res) {

                    },
                    error: function() {
                        // console.log('删除购物车所有赏评接口返回失败');
                    }
                })
            })
        },
        // cart1操作渲染
        renderUpgrate: function(res) {
            var buyInfoList = res.data.buyInfoList;
            var buyInfoListTpl = '';
            $.each(buyInfoList, function(index, item) {
                var params = JSON.parse(item.params);
                var liTpl = '';
                $.each(item.ruleGoodsNames, function(indexDir, itemDir) {
                    if(itemDir.indexOf('<strong>') != -1) {
                        liTpl += '<li>'+itemDir.split('<strong>')[0]+'<p style="color:red;font-weight:bold;">'+itemDir.split('<strong>')[1].split('</')[0]+'</p></li>';
                    } else {
                        liTpl += '<li>'+itemDir+'</p></li>';
                    }

                })
                var shoucang = '';
                if(item.fav) {
                    shoucang = '<span class="fav-on">已收藏</span>';
                } else {
                    shoucang = '<a href="javascript:void(0);" class="btn-fav" data-role="addCartFav" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-name="'+params.productName+'" data-price="'+params.price+'" data-img="'+params.image.imageId+'">收藏</a>';
                }
                var tips = '';

                if(item.count > item.store) {
                    tips = '该商品库存不足';
                }
                var shuliang = '';
                var checkbox = '';
                var huangou = '';
                var zengpin = '';
                if(item.objSource == 'GIVE') {
                    zengpin = '<span style="color:red;">[赠品]</span>'
                }
                if(item.objSource == 'TRADE_UP') {
                    huangou = '<span style="color:red;">[换购]</span>'
                }
                if(item.objSource == 'GIVE' || item.objSource == 'TRADE_UP') {
                    shuliang = '<td><div class="p-quantity" style="width:100px;">'+item.count+'</div></td>';
                    checkbox = '<input name="goods" type="checkbox" style="display:none;"/>';
                } else {
                    shuliang = '<td>\
                      <div class="p-quantity">\
                        <a href="javascript:void(0);" class="btn-decrease" data-total="'+item.store+'" data-page="cart1" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-objtype="'+item.objType+'">-</a>\
                        <input type="text" class="action-quantity-input" value="'+item.count+'" data-total="'+item.store+'" data-page="cart1" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-objtype="'+item.objType+'">\
                        <a href="javascript:void(0);" class="btn-increase" data-total="'+item.store+'" data-page="cart1" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-objtype="'+item.objType+'">+</a>\
                      </div>\
                      <p data-role="tips" style="color: red;line-height:30px;">'+tips+'</p>\
                    </td>';
                    var checkedTpl = item.selected ? 'checked="checked"' : '';
                    var objIdentTpl = item.objIdent + '_' + (item.selected ? '1' : '0');
                    checkbox = '<input name="goods" type="checkbox" data-objIdent="'+objIdentTpl+'" value="" '+checkedTpl+'/>';
                }
                buyInfoListTpl += '<tr class="cart-product" data-checked=1>\
                                      <td>'+checkbox+'</td>\
                                      <td>\
                                        <div class="p-pic">\
                                          <a href="/info.html?goodsId='+item.goodsId+'&catId='+params.catId+'" target="_blank"><img src="'+params.image.murl+'" alt="'+params.productName+'"></a>\
                                      </div></td>\
                                      <td class="p-info">\
                                        <div class="p-title"><a target="_blank" href="/info.html?goodsId='+item.goodsId+'&catId='+params.catId+'">'+params.productName+huangou+zengpin+'</a></div>\
                                        <div class="p-spec fix-empty"></div>\
                                        <div class="p-promotion">\
                                             <ul>'+liTpl+'</ul>\
                                        </div>\
                                      </td>\
                                      <td class="p-price" data-gwjs="allMoney">¥'+params.price+'</td>'+shuliang+'<td class="p-discount" data-gwjs="saveMoney" data-save="'+item.saveMoney+'">¥'+item.saveMoney+'</td>\
                                      <td class="p-integral" data-gwjs="score" data-score="'+item.score+'">'+item.totalScore+'</td>\
                                      <td class="p-subtotal" data-chae="'+(item.price - item.saveMoney)+'" data-gwjs="real">¥'+item.subtotalPrice+'</td>\
                                      <td class="p-action">'+shoucang+'<i>|</i>\
                                        <a href="javascript:void(0);" class="btn-delete" data-objIdent="'+item.objIdent+'" data-role="settleDel">移除</a>\
                                      </td>\
                                    </tr>';
            })
            $('#product_main_items_list').html(buyInfoListTpl);
            $('#order_promotion').show();
            // 订单优惠
            var orderRuleApplyInfos = res.data.payResultInfo.orderRuleApplyInfos == null ? [] : res.data.payResultInfo.orderRuleApplyInfos;
            var orderRuleApplyInfostpl = '';
            if(orderRuleApplyInfos.length) {
                $.each(orderRuleApplyInfos, function(index, item) {
                    if(item.desc!= null) {
                        orderRuleApplyInfostpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'<span style="color:#ef4521;">('+item.desc+')</span></li>';
                    } else {
                        orderRuleApplyInfostpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'</li>';
                    }
                })
            } else {
                orderRuleApplyInfostpl += '<li>无</li>'
            }
            $('[data-role="ddyh"]').html(orderRuleApplyInfostpl);

            var tradeUpObjInfos = res.data.payResultInfo.tradeUpObjInfos == null ? []: res.data.payResultInfo.tradeUpObjInfos;
            var tradeUpObjInfostpl = '';
            if(tradeUpObjInfos.length) {
                $.each(tradeUpObjInfos, function(index, item) {
                    if(!item.hasTrade) {
                        tradeUpObjInfostpl += '<li><img style="width:748px;cursor:pointer;" src="'+item.adPic+'" data-role="trade" data-ruleid="'+item.ruleId+'" data-objbn="'+item.objBn+'"/></li>';
                    }
                })
            }
            $('[data-role="ddyh"]').append(tradeUpObjInfostpl);
            if(orderRuleApplyInfos.length <= 0 && tradeUpObjInfos.length <= 0) {
                $('#order_promotion').hide();
            }
            $('#order_song').show();
            // 多级赠送
            var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;
            var giveObjInfostpl = '';
            if(giveObjInfos.length) {
                $.each(giveObjInfos, function(index, item) {
                    if(item.showSelect) {
                        giveObjInfostpl += '<div class="djzs-item"><div>'+item.ruleName+'</div>';
                        $.each(item.giveObjInfoList, function(indexDir, itemDir) {
                            if(itemDir.fit) {
                                if(itemDir.selected) {
                                    var inputTpl = '<input type="radio" name="rule'+index+'" data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'" checked="checked">';
                                } else {
                                    var inputTpl = '<input type="radio" name="rule'+index+'" data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'">';
                                }
                                giveObjInfostpl += '<div class="djzs-item__inner">\
                                                        <a href="/info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'">\
                                                            <img src="'+itemDir.picUrl+'" alt="'+itemDir.objName+'">\
                                                        </a>\
                                                        <div class="djzs-item__inners">'+inputTpl+'<a href=".javascript:;" title="'+itemDir.objName+'">'+itemDir.objName+'</a>\
                                                        </div>\
                                                    </div>';
                            }
                        })
                        giveObjInfostpl += '</div>';
                    }
                })
                giveObjInfostpl += '<div class="djzs-submit">确定</div>';
                $('[data-role="djzs"]').html(giveObjInfostpl == '<div class="djzs-submit">确定</div>' ? '无' : giveObjInfostpl);
            } else {
                $('#order_song').hide();
            }


            // 以下优惠活动正在进行中
            var orderRuleNotApplyInfos = res.data.payResultInfo.orderRuleNotApplyInfos == null ? [] : res.data.payResultInfo.orderRuleNotApplyInfos;
            var orderRuleNotApplyInfosTpl = '';
            if(orderRuleNotApplyInfos.length) {
                $.each(orderRuleNotApplyInfos, function(index, item) {
                    orderRuleNotApplyInfosTpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'</li>';
                })
            } else {
                orderRuleNotApplyInfosTpl += '<li>无</li>'
            }
            $('#contentBox').html(orderRuleNotApplyInfosTpl);

            // 运费
            var freight = res.data.payResultInfo.freight;
            $('[data-role="fee"]').html('¥'+freight);
        },
        // 浏览记录
        viewHistory: function() {
            $(document).on('click', '.history .clearAll', function() {
                wsCommon.delCookie('view_history');
                $('.history .product-list').html('');
            })
            var viewHistory = wsCommon.getCookie('view_history');
            if(viewHistory == null) {
                return;
            } else {
                $.ajax({
                    url: wsCommon.host + '/api/goods/productHistoryList',
                    dataType: wsCommon.jsonType,
                    data: {
                        productIds: viewHistory
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            var productsList = res.data.productsList ? res.data.productsList : [];

                            var productsListTpl = '';
                            $.each(productsList, function(index,item) {
                                productsListTpl += '<li class="product-item last">\
                                                      <a href="/info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" title="'+item.name+'" class="product-img"><img src="'+item.defaultImage.surl+'"></a>\
                                                      <div class="product-info"><a href="/info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" title="'+item.name+'" class="product-name">'+item.name+'</a><p class="price1"></p></div>\
                                                    </li>';
                            })
                            $('.history .product-list').html(productsListTpl);
                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            }

        },
        navList: function() {
            $.ajax({
                url: wsCommon.host + '/api/cat/list',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.data == null) return;
                        var data = res.data.goodsCats;
                        var tpl = '';
                        $.each(data, function(index, item) {
                            var cat2nameTpl = '';
                            var cat3nameTpl = '';

                            var arrorTpl = '';
                            if(item.children == null) {
                                arrorTpl = 'style="background: none"';
                            }

                            var catName = item.catName;
                            var catId = item.catId;

                            $.each(item.children ? item.children : [], function(indexDir, itemDir) {
                                cat2nameTpl += '<a href="/list1.html?catId='+itemDir.catId+'" class="level2">'+itemDir.catName+'</a>';
                                cat3nameTpl += '<dl class="sub-category clearfix"><dt><a href="/list1.html?catId='+itemDir.catId+'" class="level2">'+itemDir.catName+'</a></dt><dd class="clearfix">'
                                $.each(itemDir.children ? itemDir.children : [], function(index2Dir, item2Dir) {
                                    cat3nameTpl += '<a href="/list1.html?catId='+item2Dir.catId+'" class="level3">'+item2Dir.catName+'</a>';
                                })
                                cat3nameTpl += '</dd></dl>';
                            })

                            // 相关品牌
                            var brandTpl = '';
                            var brandList = item.brandList;
                            $.each(brandList, function(brandIndex, brandItem) {
                                brandTpl += '<a href="/brandList.html?brandId='+brandItem.brandId+'" class="item">'+brandItem.brandName+'</a>';
                            })

                            tpl += '<li class="category-item">\
                              <div class="cat-root-box"> <a href="/list1.html?catId='+item.catId+'" class="category-link" '+arrorTpl+'>'+item.catName+'</a>\
                                <div class="cat-lv2-redundancy">'+cat2nameTpl+'</div>\
                              </div>\
                              <div class="cat-children-box clearfix" style="top: 0px;">\
                                <div class="cat-children">'+cat3nameTpl+'</div>\
                                <div class="close"></div>\
                                <div class="cat-link">\
                                  <div class="cat-goto"><a href="/list1.html?catId='+catId+'" target="_blank">'+catName+'频道</a><i></i></div>\
                                  <dl class="cat-link-brand">\
                                    <dt>相关品牌</dt>\
                                    <dd>'+brandTpl+'</dd>\
                                  </dl>\
                                </div>\
                              </div>\
                            </li>';
                        })

                        $('#category_box .category-list').html(tpl);

                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })

            $('#category_box .category-list').on('click', '.close', function() {
                $(this).parents('.category-item').removeClass('active')
            })
        },
        slideNav: function(data) {
            if($('.sidecat').length == 0) return;
            var catId = wsCommon.getUrlParam('catId');
            $.ajax({
                url: wsCommon.host + '/api/cat/list',
                dataType: wsCommon.jsonType,
                data: {
                    catId: catId
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(res.data == null) return;
                        var data = res.data.goodsCats;

                        var tpl = '';

                        $.each(data, function(index, item) {
                            if(index == 0) {
                                var hrefTpl = item.parentId == 0 ? '/index.html' : '/list1.html?catId='+item.parentId
                                $('.cat_parent').html('<a href="'+hrefTpl+'" class="depth-0 e-cat-depth0-current">'+item.parentName+'</a>');
                            }

                            var dir2Tpl = '';
                            var symbolTpl = '';
                            if(item.children != null) {
                                if(item.catId == catId) {
                                    symbolTpl = '<span class="symbols Show sigud" title="隐藏" style="width:10px;height:10px;text-indent:0">-</span>';
                                } else {
                                    symbolTpl = '<span class="symbols Hide sigud" title="隐藏" style="width:10px;height:10px;text-indent:0">+</span>';
                                }
                                $.each(item.children, function(indexDir, itemDir) {
                                    dir2Tpl += '<li class="e-cat-depth-2"><a href="/list1.html?catId='+itemDir.catId+'" class="depth-2">'+itemDir.catName+'</a></li>';
                                })
                            }
                            var activeTpl = '';
                            var catDownTpl = 'style="display:none"';
                            if(item.catId == catId) {
                                activeTpl = 'is-active';
                                catDownTpl = 'style="display:block"';
                            }
                            tpl += '<li class="e-cat-depth-1 ">\
                                       <p>\
                                           <a href="/list1.html?catId='+item.catId+'" class="depth-1 '+activeTpl+'">'+item.catName+'</a>'+symbolTpl+'</p>\
                                       <ul class="cat-down" '+catDownTpl+'>'+dir2Tpl+'</ul>\
                                    </li>';
                        })
                        $('.sidecat .sidecat-wrap').html(tpl);

                        // 面包屑
                        if($('.Navigation').length) {
                            var breadCrumbs = res.data.breadCrumbs;
                            var breadCrumbsLen = breadCrumbs.length - 1;
                            var breadtpl = '<span><a href="/index.html">首页</a></span>';
                            $.each(breadCrumbs, function(index, item) {
                                if(index == breadCrumbsLen) {
                                    breadtpl += '<span style="margin: 0 4px;">&gt;</span><span class="now">'+item.catName+'</span>';
                                } else {
                                    breadtpl += '<span style="margin: 0 4px;">&gt;</span><span><a href="/list1.html?catId='+item.catId+'">'+item.catName+'</a></span>';
                                }
                            })
                            $('.Navigation').append(breadtpl);
                        }


                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },
        navHandle: function() {
            /**菜单**/
    		$("#all-category").hover(function(){
                if(window.location.href.indexOf('index') == -1 || window.location.href == wsCommon.domainhost) $("#category_box").show();
    			},function(){
                    if(window.location.href.indexOf('index') == -1 && window.location.href != wsCommon.domainhost) $("#category_box").hide();

    			})

         $(document).on('mouseenter', ".category-item", function() {
             if($(this).find('.cat-children').find('dl').length == 0) {

             } else {
                 $(this).addClass("active");
                 var menuindex = $(this).parent().children("li").index($(this));
    			 var menuconH = $(this).children(".cat-children-box").height();
    			 if(menuconH<90*(1+menuindex)){
    				 $(this).children(".cat-children-box").css("top",90*(1+menuindex)-menuconH);
    			 }
             }
         }).on('mouseleave', ".category-item", function() {
             $(this).removeClass("active");
         })

    		/**左侧菜单**/
    		$(document).on('click','.e-cat-depth-1 p',function(){
                if($(this).find('.symbols').length == 0) return;
    			var symbo = $(this).children(".symbols");
    			$(this).next("ul").toggle();
    			if(symbo.hasClass("Show")){
    				symbo.removeClass("Show").addClass("Hide").html("+");
    				}else{
    			    symbo.removeClass("Hide").addClass("Show").html("-");
    				}
    		})
        },
        // 热门搜索词
        hotSearch: function() {
            $.ajax({
                url: wsCommon.host + '/api/index/hotsearch',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        var tpl = '';
                        $.each(res.data, function(index, item) {
                            tpl += '<li><a href="/list1.html?catId='+item.catId+'" target="_blank">'+item.name+'</a></li>';
                        })
                        $('.qfnavs').append(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function() {}
            })
        },
        topNav: function() {
            $.ajax({
                url: wsCommon.host + '/api/index/queryNav',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        var data = res.data.navMenu;
                        var tpl = '';
            			$.each(data, function(index, item) {
            				var hotImage = '';
            				if(item.imgType == 1) {
            					hotImage = '<img src="/images/gif.gif">';
            				} else if(item.imgType == 2) {
                                hotImage = '<img src="/img/new.gif">';
                            }
            				tpl += '<li><a href="'+item.targetLink+'" target="'+item.targetType+'">'+item.name+hotImage+'</a></li>';
            			})
            			$('.MenuList_571').html(tpl);
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        },
        searchBtn: function() {
            $('[data-role="searchBtn"]').on('click', function() {
                var keyword = $('input[name="search_keywords"]').val();
                if(keyword == '请输入商品关键字') {
                    window.location.href = '/search.html?keyword=';
                } else {
                    window.location.href = '/search.html?keyword=' + keyword;
                }
            })
            $('input[name="search_keywords"]').on('keypress', function(e) {
                if(e.keyCode == 13) {
                    var keyword = $('input[name="search_keywords"]').val();
                    if(keyword == '请输入商品关键字') {
                        window.location.href = '/search.html?keyword=';
                    } else {
                        window.location.href = '/search.html?keyword=' + keyword;
                    }
                }
            })


            var keyword = wsCommon.getUrlParam('keyword') || '';
            if(keyword) {
                $('input[name="search_keywords"]').val(decodeURI(escape(keyword)));
            }
        },
        getFooterNews: function() {
            $.ajax({
                url: wsCommon.host + '/api/article/queryByPageName?parentNodePagename=help',
                dataType: wsCommon.jsonType,
                data: {
                    pageSize: 9999
                },
                success: function(res) {
                    var list = res.data.list;
                    var tpl = '';
                    $.each(list, function(index, item) {
                        if(item.nodeNick != '支付/配送方式' && item.nodeNick != '新手上路') {
                            tpl += '<li class="item'+(index+1)+'">\
                                        <div class="content-list">\
                                        <h3 class="content-title">'+item.nodeNick+'</h3>\
                                        <div class="article-index-list"><ul>';
                            $.each(item.indexList, function(indexDir, itemDir) {
                                tpl += '<li class="article-index lv-1 content-item">\
                                        	<a href="/article/article-'+item.nodePagename+'-'+itemDir.articleId+'.html" title="'+itemDir.title+'" target="_blank">'+itemDir.title+'</a>\
                                        </li>';
                            })
                            tpl += '</ul></div></div></li>';
                        }
                    })
                    $('[data-role="footer-new"]').html(tpl);
                },
                error: function() {}
            })
        },
        setHeaderAngFooterLink: function() {
            $.ajax({
                url: wsCommon.host + '/api/article/queryForPageView',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    var pageFoot = res.data.pageFoot;
                    $('[data-role="header-txt1"]').html(pageFoot.psgz.title).attr('href', '/article/article-'+pageFoot.psgz.nodePagename+'-'+pageFoot.psgz.articleId+'.html');
                    $('[data-role="header-txt2"]').html(pageFoot.mfps.title).attr('href', '/article/article-'+pageFoot.mfps.nodePagename+'-'+pageFoot.mfps.articleId+'.html');

                    $('[data-role="gywm"]').attr('href', '/article/article-'+pageFoot.gywm.nodePagename+'-'+pageFoot.gywm.articleId+'.html')
                    $('[data-role="lxwm"]').attr('href', '/article/article-'+pageFoot.gywm.nodePagename+'-'+pageFoot.gywm.articleId+'.html')
                    $('[data-role="cpyc"]').attr('href', '/article/article-'+pageFoot.gywm.nodePagename+'-'+pageFoot.gywm.articleId+'.html')

                    var yqljTpl = '';
                    $.each(res.data.siteLink, function(index, item) {
                        yqljTpl += '<li><a href="'+item.href+'" target="_blank" title="'+item.linkName+'">'+item.linkName+'</a></li>';
                    })
                    $('[data-role="yqlj"]').html(yqljTpl);

                    var footerListTpl = '';
                    $.each(res.data.pic, function(index, item) {
                        footerListTpl += '<a class="promise_item" href="'+'/article/article-'+item.nodePagename+'-'+item.articleId+'.html'+'" target="_blank"><img src="http://new.chijiayd.com/images/icon'+(index + 1)+'.png"><span class="item_font">'+item.title+'</span></a>';
                    })
                    $('[data-role="footer-list"]').html(footerListTpl);
                },
                error: function() {}
            })
        },

        getPlAndSd: function() {
            $.ajax({
                url: wsCommon.host + '/api/memberComments/count',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            var data = res.data;
                            var total = Number(data.count1) + Number(data.count2);
                            if(total > 0) {
                                $('.member-menu-mod2').eq(1).find('ul').find('li').eq(0).find('a').append('<span style="color:red;">('+total+')</span>');
                            }

                        }
                    }
                },
                error: function() {}
            })
        },
        gotop: function() {
            $('#gotop').on('click', function() {
                $('body,html').animate({ scrollTop: 0 }, 200);
            })
        },
        qqkfu: function() {
            // BizQQWPA.addCustom({aty: '0', a: '0', nameAccount: 4008087916, selector: 'qqkefu'});
            // $('#qqkefu').on('click', function() {
            //     window.location.href = 'tencent://message/?uin=1559934293&Site=持家有道&Menu=yes';
            // });
        },
        qqkfu1: function() {
            $('#qqkefu1').on('click', function() {
                window.location.href = 'tencent://message/?uin=1559934293&Site=持家有道&Menu=yes';
            });
        },
        qqkfu2: function() {
            $('#qqkefu2').on('click', function() {
                window.location.href = 'tencent://message/?uin=1611737267&Site=持家有道&Menu=yes';
            });
        },
        bannersad: function() {
            $.ajax({
                url: wsCommon.host + '/api/index/banner',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.data.show) {
                            $('.bannersd').html('<a href="'+res.data.clickTarget+'" target="_blank"><img style="width:'+res.data.width+'px;height:'+res.data.height+'px" src="'+res.data.url+'"></a>');
                        }
                    }
                },
                error: function() {}
            })
        },
        ssoreTips: function() {
            if(wsCommon.getUrlParam('source') == 'login') {
                $.ajax({
    			    url: wsCommon.host + '/api/members/center',
    			    dataType: wsCommon.jsonType,
    			    success: function(res) {
    					if(res.code == 1) {
    						if(res.result) {
    							var data = res.data;

    							if(data.canUpgrade) {
    								$('.upTopsBox').show();
    								$('[data-role="point"]').html(data.point);
    								$('[data-role="discount"]').html(data.nextLevelDisCount*10);
                                    $('.upTopsBox .close').on('click', function() {
                                        $('.upTopsBox').hide();
                                    })
    							}


    						} else {
    							wsCommon.setCookie('go_back_link', window.location.href);
    							window.location.href = './passport-login.html';
    						}
    					}
    			    },
    			    error: function() {
    			        // console.log('接口返回失败');
    			    }
    			})
            }
        },
        init: function() {
            this.setTopUserInfo();
            this.toLogin();
            this.logout();
            this.initShopCartNum();
            this.listShopCart();
            this.slideListShopCart();
            this.addShopCart();
            this.contorlNum()
            this.deleteSingleShopCart();
            this.deleteAllShopCart();
            this.viewHistory();
            this.topNav();
            this.navList();
            this.slideNav();
            this.navHandle();
            this.hotSearch();
            this.searchBtn();
            this.getFooterNews();
            this.setHeaderAngFooterLink();
            this.getPlAndSd();
            this.gotop();
            this.qqkfu();
            this.qqkfu1();
            this.qqkfu2();
            this.bannersad();
            this.ssoreTips();
        }
    }

    common.init();
})
